package string;

/**
 * @Author: xpengfei
 * @Date: 2019/9/27 10:12
 * @Description：执行用时 :2 ms , 在所有 Java 提交中击败了 60.99%的用户
 * 内存消耗 :37.2 MB, 在所有 Java 提交中击败了 59.05%的用户
 */
public class Solution28 {
    public int strStr(String haystack, String needle) {
//        if (null == needle  || needle.length() == 0)
//            return 0;
//        return haystack.indexOf(needle);
        int haylen = haystack.length();
        int nedlen = needle.length();
        if(nedlen == 0 || haylen == 0) {
            if(nedlen == 0 ){return 0;}
            return  -1;
        }
        int count = 0;
        //for循环中将s.length()使用局部变量替换后，时间缩短2ms左右
        for (int i = 0; i <= haylen - nedlen; i++) {
            for (int j = 0; j < nedlen; j++) {
                    if (needle.charAt(j) == haystack.charAt(i)){
                        count++;
                        i++;
                        if (count == nedlen)
                            return i-count;
                    }else {
                        i = i-count;
                        count = 0;
                        break;
                    }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Solution28 solution28 = new Solution28();
        /*
        "mississippi"
"issipi"
         */
        String origin = "mississippi";
        String target = "pi";
        System.out.println(origin.contains(target)+"\tLocation:"+origin.indexOf(target));
        System.out.println(solution28.strStr(origin,target));
    }
}
